import os

import selenium
from selenium import webdriver
import requests as http
from selenium.webdriver.common.by import By as by
import json
from config import linkConfig, userConfig, getOrderNumsConfig
import json


def isNot(w, c, p):
    try:
        w.find_element(c, p)
        return True
    except:
        return False


def getOrderNums():
    # 获取订单号
    api = 'http://192.168.5.158/Order/GetJDOrderList'
    res = http.post(url=api, data=getOrderNumsConfig)
    if res.status_code != 200:
        print('访问获取订单号接口失败')
        assert 0

    res = json.loads(res)
    print(res)
    orderNums = res['data']['outOrderNumber']
    print(f'订单号：{orderNums}')
    return orderNums


def runMain():
    print('开始执行Testfun')
    web = webdriver.Chrome()
    # 隐等待
    web.implicitly_wait(10)
    # 窗口最大化
    web.maximize_window()
    # 访问登陆api
    web.get(linkConfig['indexApi'])

    if os.path.exists('cookie.txt'):
        with open('cookie.txt', 'r', encoding='utf8') as f:
            listCookies = json.loads(f.read())
            print(f'cookie -->>  {listCookies}')
            for cookie in listCookies:
                web.add_cookie(cookie)
            # 读取完cookie刷新页面
            web.refresh()

    # 判断是否登陆
    if isNot(web, by.XPATH, '//*[@id="ttbar-login"]/div/a'):
        pass
    else:
        print('前往登陆')
        web.get('https://passport.jd.com/new/login.aspx')
        print('获取地址信息')
        # print('data -- >> '+data)
        print('-----------')
        login = web.find_element(by.XPATH, '//*[@id="content"]/div[2]/div[1]/div/div[3]/a')
        login.click()
        # time.sleep(10)
        user_edit = web.find_element(by.XPATH, '//*[@id="loginname"]')
        pass_edit = web.find_element(by.XPATH, '//*[@id="nloginpwd"]')
        login_button = web.find_element(by.XPATH, '//*[@id="loginsubmit"]')
        user_edit.send_keys(userConfig['user'])
        pass_edit.send_keys(userConfig['pass'])
        login_button.click()

        # user_view = web.find_element(by.XPATH, '//*[@id="ttbar-login"]/div/a')
        assert isNot(web, by.XPATH, '//*[@id="ttbar-login"]/div/a')
        print('成功登录')

        # 获取cookie
        dictCookies = web.get_cookies()
        jsonCookies = json.dumps(dictCookies)
        # print(jsonCookies)
        with open('cookie.txt', 'w') as f:
            f.write(jsonCookies)

    i = 0
    orders_shipped = []
    while True:
        i = i+1
        # 获取订单号
        orders = getOrderNums()
        print(f'开始第{i}次w循环')
        for key in orders:
            order = orders[key]['outOrderNumber']
            print(f'本次订单号为：{order}')
            if order in orders_shipped:
                print('此订单号已发货')
                continue
            # 前往该订单界面
            web.get(f'https://order.jd.com/center/search.action?keyword={order}')
            order_status = web.find_element(by.CLASS_NAME, "order-status")
            order_status_text = order_status.text
            if order_status_text == '已发货':
                orders_shipped.append(order)


if __name__ == '__main__':
    runMain()
